package com.tuniu.agents.common.filter;

import com.tuniu.agents.common.AgentsConstants;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Component
public class ConversationIdArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        // Check if the parameter is the conversation ID and of type String
        return AgentsConstants.AgentsConversationEnvironmentKey.CONVERSATION_ID.equals(parameter.getParameterName()) &&
                parameter.getParameterType().equals(String.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        // Get the conversation ID from the request header
        String conversationId = webRequest.getHeader(AgentsConstants.AgentsConversationEnvironmentKey.CONVERSATION_ID);
        if (!StringUtils.hasText(conversationId)) {
            // Get the conversation ID from the request attributes
            conversationId = (String) webRequest.getAttribute(
                    AgentsConstants.AgentsConversationEnvironmentKey.CONVERSATION_ID, RequestAttributes.SCOPE_REQUEST);
        }
        return conversationId;
    }
}
